package com.restaurantonlineorder.seller.exceptionhandler;

import com.restaurantonlineorder.exception.PermissionDeniedException;
import com.restaurantonlineorder.response.BaseResult;
import com.restaurantonlineorder.response.BaseResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 全局处理异常
 *
 * @author 熊宇
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 请求参数绑定异常 处理
     *
     * @param validException
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.OK)
    public BaseResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException validException) {
        log.error(validException.getMessage());

        //获取所有异常参数信息
        List<FieldError> errors = validException.getBindingResult().getFieldErrors();
        Stream<FieldError> stream = errors.stream();
        Collection<String> errorMessages = stream.map(e -> e.getDefaultMessage())
                .collect(Collectors.toList());

        return BaseResult.failure(BaseResultCode.DATA_IS_WRONG, errorMessages);
    }

    /**
     * 请求参数校验异常 处理
     *
     * @param constraintViolationException
     * @return
     */
    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseStatus(HttpStatus.OK)
    public BaseResult constraintViolationExceptionExceptionHandler(ConstraintViolationException constraintViolationException) {

        Set<ConstraintViolation<?>> constraintViolations = constraintViolationException.getConstraintViolations();
        Stream<ConstraintViolation<?>> constraintViolationStream = constraintViolations.stream();
        List<String> errorMessages = constraintViolationStream.map(e -> e.getMessage())
                .collect(Collectors.toList());


        return BaseResult.failure(BaseResultCode.DATA_IS_WRONG, errorMessages);
    }

    /**
     * 权限异常处理器
     *
     * @param permissionDeniedException 权限异常
     * @return
     */
    @ExceptionHandler({PermissionDeniedException.class})
    @ResponseStatus(HttpStatus.OK)
    public BaseResult permissionDeniedExceptionHandler(PermissionDeniedException permissionDeniedException) {
        return BaseResult.failure(BaseResultCode.PERMISSION_NO_ACCESS, permissionDeniedException.getMessage());
    }

}
